admin = 'root'
roledict = {'owner1':'sri'}
if 'owner' in roledict:
owner = roledict['owner']
else:
owner = admin
(-1) for looking up owner twice
(-1) requires 4 lines and an indent
Dictionaries support a get method that provides a default value to assign if a key is not present.
owner = roledict.get('owner', admin)
print(owner)
for item in items:
if is_for_sale(item):
cost = compute_cost(item)
if cost <= wallet.money:
buy(item)
(-1) actual buy() is buried 2 level deep.
Also, we are identing the code so far, eventually you have 120 spaces on a line before actual code begins. One way to write a cleaner code is to test the opposite of each of your tests.
for item in items:
if not is_for_sale(item):
continue
cost = compute_cost(item)
if cost <= wallet.money:
continue
buy(item)
Object-Oriented design patterns are specifically about putting the big pieces of an application together.
* Classes
* Objects
* References
1st principle in Design Patterns:
"Program to an interface not an implementation"
Problem: static typing locks you in (there is only one class named File)
```public void writeZen(File out) {
out.write ('Beautiful is bettern than ugly')
}```
Solution: do not mention actual types (any class can implement IWritable)
```public void writeZen(IWritable out) {
out.write ('Beautiful is bettern than ugly')
}```
Why would you do this?
Because someday you might want to write to something that is file-like but not an actual File!
Because in python we throw static typing overboard and instead use duck typing, we don't need to worry about the above rule. The language itself provides us with the feature.
def writeZen(out):
out.write('Beautifule is better than ugly')
This function accepts anything and simply risks an exception if the duck refuses to quack.
More about ducktyping can be found at - http://www.ics.uci.edu/~shirano/ics32/CodeExamples/DuckTyping/
So a language feature "Python is dynamic" and does not make you pre-specify the types accepeted by a function
-eliminates a whole Gang Of Four design principle! In other words - All python code you have ever written
automatically adheres to the GoF principle that functions should not name the classes that can be passed in. Unless
you add inflexibility manually with isinstance() tests (i.e., using isinstance tests is strongly discouraged).
Python is brilliant. No separate syntax for object instantiation.
In python you cannot tell what is being called:
t = thing()
It can be whatever it's author needed. You can tell the difference if you isinstance() with the constructor - but you would not do that, right?
t = thing()
isinstance(t, thing)
In [ ]: